package com.jy.api.controller.common;

import com.jy.api.dao.OrderDao;
import com.jy.api.dao.WorkShiftDao;
import com.jy.api.domain.WorkShift;
import com.jy.api.service.WechatTemplateService;
import com.jy.api.service.WorkshiftService;
import com.jy.api.signUpReq.pos.WorkshiftSignUpReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.Date;

/**
 * Created by lihu on 2018/3/24.
 */
@Slf4j
@RequestMapping(value = "/v1/shift", produces = "application/json;charset=utf-8")
@RestController
public class GatewayShiftController {


    @Autowired
    WorkShiftDao workShiftDao;


    @Autowired
    WorkshiftService workshiftService;


    @Autowired
    private OrderDao orderDao;

    @Autowired
    WechatTemplateService wechatTemplateService;


    /**
     * 同步交班信息
     *
     * @param id
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/workshift/{id}")
    public ResponseEntity putWorkshift(@PathVariable(name = "id") String id, Principal principal) {
        try {
            WorkShift workShift = workShiftDao.findOne(id);
            if (workShift.isClosed()) {
                return new ResponseEntity("当前班次已完结", HttpStatus.BAD_REQUEST);
            }
            //处理 待处理订单
            orderDao.updateUnfinishedOrder(workShift.getStoreId(), workShift.getBeginTime());
            //处理 失败订单状态
            orderDao.updateFailOrder(workShift.getStoreId(), workShift.getBeginTime());
            workShift.setCloseUserId(workShift.getOperatorId());
            workShift.setCloseUsername(workShift.getOperatorName());
            workShift.setEndTime(new Date());
            //数据校正
            workshiftService.synchWorkshift(workShift,  principal.getName());
            //交班信息推送
            wechatTemplateService.sendWorkshift(workShift, null);

            return new ResponseEntity(HttpStatus.OK);
        } catch (Exception ex) {
            log.error("putWorkshift is error==> id:{},WorkshiftSignUpReq:{}", id, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
